package com.superhero.common.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


public class ExcelUtils {

    final static String RESPONSE_HEAD_CONTENT_TYPE = "application/octet-stream;charset=UTF-8";
    final static String CONTENT_DISPOSITION = "Content-Disposition";
    final static String ATTACHMENT_FILENAME = "attachment;filename=down.xlsx";

    /**
     * 导出文件工具类
     *
     * @param name
     * @param response
     * @param writer
     * @throws IOException
     */
    public static void responseExcel(String name, HttpServletResponse response, ExcelWriter writer) throws IOException {

        //1. response为HttpServletResponse对象
        response.setContentType(RESPONSE_HEAD_CONTENT_TYPE);

        //2. 设置头部信息
        response.setHeader(CONTENT_DISPOSITION, ATTACHMENT_FILENAME);

        ServletOutputStream out = response.getOutputStream();

        //3. 将文件写出到流。
        writer.flush(out, true);

        //4. 关闭writer，释放内存
        writer.close();

        //5. 关闭输出Servlet流
        IoUtil.close(out);

    }

    /**
     * 进行 excel 操作
     *
     * @param titleName excel 第一行，不传入则不生成
     * @param writer    构建好的 ExcelWriter
     * @param dataList  excel 中数据的集合
     * @param clazz     excel 中数据的集合的对象类，非 map;
     * @return
     */
    public static ExcelWriter doExcelWriter(String titleName, ExcelWriter writer, List dataList, Class clazz) {
        int length = 0;
        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
            length += clazz.getDeclaredFields().length;
        }
        if (ObjectUtil.isNotEmpty(titleName)) {
            writer.merge(length, titleName);
        }

        writer.write(dataList, true);

        Workbook workbook = writer.getWorkbook();
        DataFormat dataFormat = workbook.createDataFormat();

        for (int i = 0; i < length; i++) {

            writer.getCellStyle().setDataFormat(dataFormat.getFormat("@"));

            try {
                writer.getSheet().autoSizeColumn(i);
                writer.getSheet().setColumnWidth(i, writer.getSheet().getColumnWidth(i) * 17 / 10);
            } catch (Exception e) {
                //字段超过 255 个字符时不支持修改单元格自适应长度。
                writer.getSheet().setColumnWidth(i, 30 * 256);
            }
        }
        return writer;
    }
}
